/**
 * @fileoverview Fichero inicial de ejecución.
 * @author folcwine@gmail.com (José Cabo)
 * @author igcogi@gmail.com (Ignacio José Codoñer)
 */

var io = require('socket.io')
	,moo = require('./libs/MooTools1.3.2s')
	,chat = require('./chat.js');
var io = require('socket.io').listen(5555); // for npm, otherwise use require('./path/to/socket.io')

//Mootools req.
require('./libs/MooTools1.3.2s').apply(GLOBAL);

//Game super object.
var chat = require('./chat.js').getChat();

io.sockets.on('connection', function(socket){

	console.log("Nuevo socket creado.");

	//Extend main client object
	var client = require('./client.js').newClient();
	client.socket = socket;
	client.id = socket.id;
	
	chat.newClientConnected(client);
	
	//Receive a command
	socket.on('command', function(command){
		console.log("Nuevo comando.");
		
		//Execute command.
		var answer = chat.executeCommandForClient(client, command);
		
		if(answer.command)
			chat.sendAnswerForAll(client, answer);
		else //Send answer or confirmation.
			chat.sendAnswer(client, answer);
	});
	
	//Receive an asnwer.
	socket.on('answer', function(a){
		console.log("answer received for: "+a.idc+". OK.");
		chat.processAnswerForClient(client, a);
	});
	socket.on('disconnect', function(){
		chat.clientDisconnected(client);
		console.log("Socket Desconectado.");
	});
});
